package tk.mynoteapp.dev.other.eliminateifelse.right.annotations;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 1、使用注解
 * 实现了ApplicationListener接口，这样在onApplicationEvent方法中，就可以拿到ApplicationContext的实例。
 * 再获取了PayCode注解的类，放到一个map中，map中的key就是PayCode注解中定义的value，跟code参数一致，value是支付类的实例
 *
 * 注：code可以没有业务含义，允许是纯数字，只要不重复即可
 */
@Service
public class PayService implements ApplicationListener<ContextRefreshedEvent> {
    private static Map<String, IPay> payMap = null;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(PayCode.class);
        if (beansWithAnnotation != null) {
            payMap = new HashMap<>();
            beansWithAnnotation.forEach((key, value) -> {
                String bizType = value.getClass().getAnnotation(PayCode.class).value();
                payMap.put(bizType, (IPay) value);
            });
        }
    }

    public void pay(String code) {
        payMap.get(code).pay();
    }
}
